package com.example.viewtest.gesture_12;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.example.viewtest.R;
import com.example.viewtest.Utils;

/**
 * 配合型多点触控
 */
public class CooperateGestureView extends View {

    private Bitmap bitmap;
    private Paint paint;

    private float locationX;
    private float locationY;

    private float downX;
    private float downY;
    private float originX;
    private float originY;

    public CooperateGestureView(Context context) {
        this(context, null);
    }

    public CooperateGestureView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CooperateGestureView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        bitmap = Utils.getBitmap(getResources(), R.mipmap.head, (int) Utils.db2px(200));
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int count = event.getPointerCount();
        float x = 0, y = 0;
        for (int i = 0; i < count; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= count;
        y /= count;

        int masked = event.getActionMasked();
        switch (masked) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                downX = x;
                downY = y;
                originX = locationX;
                originY = locationY;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                //当手指放开时，xy的平均值需要重新计算，扣掉放开的那个手指
                int upIndex = event.getActionIndex();
                x = 0;
                y = 0;
                for (int i = 0; i < count; i++) {
                    if (i != upIndex) {
                        x += event.getX(i);
                        y += event.getY(i);
                    }
                }
                downX = x / (count - 1);
                downY = y / (count - 1);
                originX = locationX;
                originY = locationY;
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = x - downX;
                float moveY = y - downY;
                locationX = originX + moveX;
                locationY = originY + moveY;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, locationX, locationY, paint);
    }
}
